package com.ruoyi.product.controller;

import java.util.*;

import com.ruoyi.common.minio.server.MinioService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.product.domain.ProductImage;
import com.ruoyi.product.service.IProductImageService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 商品图片Controller
 * 
 * @author liuhizhong
 * @date 2025-07-11
 */
@RestController
@RequestMapping("/product/productImage")
public class ProductImageController extends BaseController
{
    @Autowired
    private IProductImageService productImageService;

    @Autowired
    private MinioService minioService;

    @Value("${minio.bucket-name}")
    private String bucketName;

    /**
     * 上传SKU图片到MinIO
     */
    /**
     * 上传SKU图片到MinIO（支持多文件上传）
     */
    @PostMapping("/upload")
    @SneakyThrows
    public AjaxResult uploadSkuImage(@RequestParam("files") MultipartFile[] files,
                                     @RequestParam("skuId") Long skuId) {
        List<Map<String, Object>> results = new ArrayList<>();

        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                // 生成文件名
                String originalFileName = file.getOriginalFilename();
                String fileExtension = "";
                if (originalFileName != null && originalFileName.contains(".")) {
                    fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
                }
                String fileName = System.currentTimeMillis() + "_" + new Random().nextInt(1000) + fileExtension;

                // 上传文件到MinIO
                Map<String, String> uploadResult = minioService.uploadFile(file, fileName);

                if (uploadResult != null && "true".equals(uploadResult.get("success"))) {
                    // 保存图片信息到数据库
                    ProductImage productImage = new ProductImage();
                    productImage.setSkuId(skuId);
                    productImage.setUrl(uploadResult.get("fileUrl"));
                    productImage.setSort(0L); // 默认排序为0

                    int result = productImageService.insertProductImage(productImage);
                    if (result > 0) {
                        Map<String, Object> resultMap = new HashMap<>();
                        // 返回给前端
                        resultMap.put("imageUrl", uploadResult.get("fileUrl"));
                        resultMap.put("imageId", productImage.getId());
                        resultMap.put("fileName", originalFileName);
                        results.add(resultMap);
                    }
                }
            }
        }
        if (!results.isEmpty()) {
            return AjaxResult.success("上传成功", results);
        }
        return error("上传失败");
    }

    /**
     * 删除商品图片（同时删除MinIO中的文件）
     */
    @Log(title = "商品图片", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{id}")
    public AjaxResult deleteSkuImage(@PathVariable Long id) {
        // 获取图片信息
        ProductImage productImage = productImageService.selectProductImageById(id);
        if (productImage == null) {
            return AjaxResult.error("图片不存在");
        }

        try {
            // 从URL中提取文件名
            String imageUrl = productImage.getUrl();
            if (imageUrl != null && !imageUrl.isEmpty()) {
                // 提取文件名，URL格式为 http://minio-server/bucket-name/filename
                String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);

                // 删除MinIO中的文件
                minioService.deleteFile(bucketName, fileName);
            }

            // 从数据库中删除记录
            int result = productImageService.deleteProductImageById(id);
            if (result > 0) {
                return AjaxResult.success("删除成功");
            } else {
                return AjaxResult.error("删除失败");
            }
        } catch (Exception e) {
            logger.error("删除图片失败", e);
            return AjaxResult.error("删除图片失败: " + e.getMessage());
        }
    }

    /**
     * 查询商品图片列表
     */
//    @PreAuthorize("@ss.hasPermi('product:productImage:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(ProductImage productImage)
//    {
//        startPage();
//        List<ProductImage> list = productImageService.selectProductImageList(productImage);
//        return getDataTable(list);
//    }

    /**
     * 获取商品图片详细信息
     */
    @PreAuthorize("@ss.hasPermi('product:productImage:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(productImageService.selectProductImageById(id));
    }

    /**
     * 新增商品图片
     */
    @PreAuthorize("@ss.hasPermi('product:productImage:add')")
    @Log(title = "商品图片", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProductImage productImage)
    {
        return toAjax(productImageService.insertProductImage(productImage));
    }

    /**
     * 修改商品图片
     */
    @PreAuthorize("@ss.hasPermi('product:productImage:edit')")
    @Log(title = "商品图片", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProductImage productImage)
    {
        return toAjax(productImageService.updateProductImage(productImage));
    }

    /**
     * 删除商品图片
     */
    @PreAuthorize("@ss.hasPermi('product:productImage:remove')")
    @Log(title = "商品图片", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(productImageService.deleteProductImageByIds(ids));
    }
}
